package com.i2863.receipt.controller;

import com.i2863.receipt.entity.Activity;
import com.i2863.receipt.entity.Receipt;
import com.i2863.receipt.entity.Site;
import com.i2863.receipt.entity.Winner;
import com.i2863.receipt.service.ActivityService;
import com.i2863.receipt.service.ReceiptService;
import com.i2863.receipt.service.SiteService;
import com.i2863.receipt.service.WinnerService;
import com.i2863.receipt.util.ResultJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/6/8.
 */
@Controller
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private WinnerService winnerService;

    @Autowired
    private ReceiptService receiptService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    private final static Logger logger = LoggerFactory.getLogger(ActivityController.class);

    private static int PAGESIZE = 10;

    /**
     * 活动列表
     * @param modelMap
     * @param startTime 活动开始时间
     * @param endTime 活动结束时间
     * @param pageNum 页码
     * @param queryContent 查询关键字
     * @return
     */
    @RequestMapping("/getlist")
    public String getlist(ModelMap modelMap,
                          @RequestParam(value = "startTime",required = false)String startTime,
                          @RequestParam(value = "endTime",required = false)String endTime,
                          @RequestParam(value = "pageNum",required = false,defaultValue = "1")Integer pageNum,
                          @RequestParam(value = "queryContent",required = false)String queryContent){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        Page<Activity> page = activityService.queryByPage(siteId,PAGESIZE,pageNum,queryContent,startTime,endTime);
        List<Activity> list = page.getContent();
        modelMap.put("list",list);
        modelMap.put("total",page.getTotalElements());
        modelMap.put("pageNum",pageNum);
        modelMap.put("startTime",startTime);
        modelMap.put("endTime",endTime);
        modelMap.put("pageSize",PAGESIZE);
        modelMap.put("queryContent",queryContent);
        modelMap.put("now",new Date().getTime());
        return "activity/list";
    }


    /**跳转到添加活动页面
     *
     * @return
     */
    @RequestMapping("/toAdd")
    public String add(){
        return "activity/add";
    }


    /**
     * 保存
     * @param activity
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public String save(Activity activity,
                       @RequestParam(value = "startDate",required = true)String startDate,
                       @RequestParam(value = "endDate",required = true)String endDate){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        Integer outsideNum = activity.getEnrollNum()-activity.getInsideNum();
        List<Activity> actList = activityService.findListBySiteId(siteId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime;
        Date endTime;
        try {
            startTime = format.parse(startDate+" 00:00:00");
            endTime = format.parse(endDate+" 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
            logger.error("日期转换异常");
            return ResultJson.errorMes("日期格式异常");
        }
        for (Activity entity : actList) {
            if(startTime.getTime()>=entity.getStartTime().getTime()&&startTime.getTime()<=entity.getEndTime().getTime()){
                return ResultJson.errorMes("活动开始时间与其他活动时间重叠");
            }
            if(endTime.getTime()>=entity.getStartTime().getTime()&&endTime.getTime()<=entity.getEndTime().getTime()){
                return ResultJson.errorMes("活动结束时间与其他活动时间重叠");
            }
        }
        if(outsideNum<=0){
            return ResultJson.errorMes("场内人数大于入围人数");
        }
        activity.setOutsideNum(outsideNum);
        activity.setActivityStatus(Activity.NOTSTARTED);


        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        Site site = siteService.findOne(siteId);
        activity.setSite(site);
        Integer count = activityService.getMaxActivityNum(siteId);
        if(count==null){
            count=0;
        }
        activity.setNum(count+1);//活动期数
        activityService.add(activity);
        return ResultJson.successMeg("保存成功");
    }

    /**
     *跳转修改页面
     * @param activityId 活动id
     * @return
     */
    @RequestMapping("/toedit")
    public String toEdit(Integer activityId,ModelMap modelMap){
        Activity activity = activityService.findOne(activityId);
        modelMap.put("activity",activity);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = format.format(activity.getStartTime());
        String endDate = format.format(activity.getEndTime());
        modelMap.put("startDate",startDate);
        modelMap.put("endDate",endDate);
        return "activity/edit";
    }

    /**
     * 修改
     * @param activity
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(Activity activity,
                         @RequestParam(value = "startDate",required = true)String startDate,
                         @RequestParam(value = "endDate",required = true)String endDate){
        Activity entity = activityService.findOne(activity.getId());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime;
        Date endTime;
        try {
            startTime = format.parse(startDate+" 00:00:00");
            endTime = format.parse(endDate+" 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
            logger.error("日期转换异常");
            return ResultJson.errorMes("日期格式异常");
        }
        entity.setStartTime(startTime);
        entity.setEndTime(endTime);
        Integer outSaidNum = activity.getEnrollNum()-activity.getInsideNum();
        if(outSaidNum<=0){
            return ResultJson.errorMes("场内人数大于入围人数");
        }
        entity.setOutsideNum(outSaidNum);
        entity.setAmountLow(activity.getAmountLow());
        entity.setEnrollNum(activity.getEnrollNum());
        entity.setName(activity.getName());
        entity.setInsideNum(activity.getInsideNum());
        activityService.update(entity);
        return ResultJson.successMeg("修改成功");
    }

    /**
     * 删除（可批量）
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public String del(@RequestParam(value = "ids")String ids){
        String[] idArray = ids.split(",");
        List<Integer> idlist = new ArrayList<Integer>();
        for (String id : idArray) {
            idlist.add(Integer.parseInt(id));
        }
        List<Activity> activities = activityService.findListByIds(idlist);
        for(Activity activity:activities){
            Integer status = activity.getActivityStatus();
            if(status==Activity.STARTED||status==Activity.SECOND_ROUND){//如果存在状态为未开始和已结束的活动，就不能删
                return ResultJson.errorMes("不能删除正在进行中的活动");
            }
        }
        //删除活动时  要关联删除活动下的发票和活动下的中奖纪录
        for (Activity activity : activities) {
            List<Receipt> receipts = activity.getReceiptList();
            List<Winner> winners = activity.getWinngList();
            if(receipts.size()>0&&receipts!=null){
                receiptService.del(receipts);
            }
            if(winners.size()>0&&winners!=null){
                winnerService.del(winners);
            }
        }
        activityService.del(activities);
        return ResultJson.successMeg("删除成功");
    }


    /**
     * 设置活动状态为结束
     * @param id 活动id
     * @return
     */
    @RequestMapping("/finishActivity")
    @ResponseBody
    public String finishActivity(@RequestParam(value = "id",required = true)Integer id){
        activityService.finishActivity(id);
        return ResultJson.successMeg("设置成功");
    }

    /**
     * 验证人数
     * @param id
     * @return
     */
    @RequestMapping("/validatePeopleNum")
    @ResponseBody
    public String validatePeopleNum(Integer id){
        Integer peopleNum = receiptService.countByActivityId(id);
        Activity activity = activityService.findOneById(id);
        if(peopleNum>=(activity.getEnrollNum()+activity.getReselectionNum())){//判断参与活动的人数是否比活动设置的入围人数少
            return ResultJson.successMeg("可以开始抽奖");
        }else{
            return ResultJson.errorMes("参与人数太少,不能抽奖");
        }
    }

}
